using LangChain.NET.LLMS.OpenAi;
using Material.Mvc.Services;
using System.Collections.Concurrent;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

public class CustomerService : ICustomerService
{
    private readonly IConfiguration _configuration;
    private readonly HttpClient _httpClient;
    private readonly ConcurrentDictionary<string, List<ChatMessage>> _conversationHistories;
    private readonly string _apiKey;
    private readonly string _apiEndpoint;
    private readonly string _model;
    private readonly float _temperature;
    private readonly int _maxTokens;
    private readonly ILogger<CustomerService> _logger;

    // 构造函数
    public CustomerService(IConfiguration configuration, ILogger<CustomerService> logger)
    {
        _configuration = configuration;
        _logger = logger;

        // 初始化 _conversationHistories
        _conversationHistories = new ConcurrentDictionary<string, List<ChatMessage>>();

        // 读取配置 - 使用AI21配置节
        _apiKey = _configuration["AI21:ApiKey"] ?? throw new ArgumentNullException("AI21 API key is missing");
        _apiEndpoint = _configuration["AI21:ApiEndpoint"] ?? "https://api.ai21.com/studio/v1/maestro/runs";
        _temperature = float.TryParse(_configuration["AI21:Temperature"], out var temp) ? temp : 0.7f;
        _maxTokens = int.TryParse(_configuration["AI21:MaxTokens"], out var tokens) ? tokens : 500;

        // 初始化 HTTP 客户端
        _httpClient = CreateHttpClientWithProxy();

        // 设置 Authorization 头部
        _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _apiKey);

        _logger.LogInformation("CustomerService initialized successfully with API key ending in: {ApiKeyEnding}", _apiKey.Substring(Math.Max(0, _apiKey.Length - 5)));
    }

    // 创建 HttpClient 并配置代理
    private HttpClient CreateHttpClientWithProxy()
    {
        var clientHandler = new HttpClientHandler();

        // 使用代理
        if (_configuration.GetValue<bool>("Proxy:Enabled"))
        {
            var proxyAddress = _configuration["Proxy:Address"];
            var proxyPort = _configuration.GetValue<int>("Proxy:Port");

            // 检查代理地址和端口是否有效
            if (string.IsNullOrEmpty(proxyAddress) || proxyPort == 0)
            {
                _logger.LogError("代理地址或端口配置无效，无法设置代理");
                throw new InvalidOperationException("代理地址或端口配置无效");
            }

            try
            {
                clientHandler.Proxy = new WebProxy(proxyAddress, proxyPort);
                _logger.LogInformation("代理已成功配置，代理地址: {ProxyAddress}:{ProxyPort}", proxyAddress, proxyPort);
            }
            catch (Exception ex)
            {
                _logger.LogError("设置代理时发生错误: {Message}", ex.Message);
                throw new InvalidOperationException("无法配置代理", ex);
            }
        }
        else
        {
            _logger.LogInformation("代理未启用，使用默认网络设置");
        }

        var client = new HttpClient(clientHandler);
        return client;
    }

    // 处理用户消息
    public async Task<string> ProcessMessageAsync(string userId, string message)
    {
        try
        {
            _logger.LogInformation("Processing message from user: {UserId}", userId);
            _logger.LogInformation("Message content: {Message}", message);
    
            // 参数验证
            if (string.IsNullOrWhiteSpace(userId))
            {
                _logger.LogError("Invalid userId provided");
                return "抱歉，无法处理您的消息，请稍后再试。";
            }
    
            if (string.IsNullOrWhiteSpace(message))
            {
                _logger.LogError("Empty message provided");
                return "您的消息为空，请输入有效的内容。";
            }
    
            // 获取或创建用户的对话历史
            var history = _conversationHistories.GetOrAdd(userId, _ => new List<ChatMessage>());
            if (history == null)
            {
                _logger.LogError("Failed to get conversation history for user: {UserId}", userId);
                return "无法获取对话历史，请稍后再试。";
            }
    
            _logger.LogInformation("Current conversation history count: {HistoryCount}", history.Count);
    
            // 创建符合AI21 Maestro API要求的请求体
            var requestBody = new
            {
                input = message,
                settings = new
                {
                    temperature = _temperature,
                    maxTokens = _maxTokens
                }
            };
    
            string jsonContent;
            try
            {
                jsonContent = JsonSerializer.Serialize(requestBody);
                _logger.LogDebug("Request body serialized successfully");
            }
            catch (JsonException jsonEx)
            {
                _logger.LogError("Failed to serialize request body: {Message}", jsonEx.Message);
                return "处理您的请求时发生错误，请稍后再试。";
            }
    
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
    
            _logger.LogInformation("Sending request to AI21 API endpoint: {ApiEndpoint}", _apiEndpoint);
            _logger.LogInformation("Using API key ending with: {ApiKeyEnding}", _apiKey.Substring(Math.Max(0, _apiKey.Length - 5)));
    
            try
            {
                _logger.LogInformation("Starting API request...");
                var response = await _httpClient.PostAsync(_apiEndpoint, content);
    
                _logger.LogInformation("Received response from AI21 API with status code: {StatusCode}", response.StatusCode);
    
                // Log the full response body for debugging purposes
                var responseBody = await response.Content.ReadAsStringAsync();
                _logger.LogInformation("Raw response body from AI21 API: {ResponseBody}", responseBody);
    
                if (!response.IsSuccessStatusCode)
                {
                    _logger.LogError("AI21 API error - Status: {StatusCode}, Content: {ErrorContent}", response.StatusCode, responseBody);
                    return $"AI21 服务暂时不可用 [错误码: {response.StatusCode}]，请稍后再试。";
                }
    
                // 解析 AI21 API 响应
                AI21Response? result = null;
                try
                {
                    result = JsonSerializer.Deserialize<AI21Response>(responseBody);
                }
                catch (JsonException jsonEx)
                {
                    _logger.LogError("Failed to deserialize AI21 response: {Message}", jsonEx.Message);
                    _logger.LogInformation("Problematic response: {ResponseBody}", responseBody);
                    return "处理AI21回复时发生错误，请稍后再试。";
                }
    
                if (result == null)
                {
                    _logger.LogError("AI21 API returned null response");
                    return "未能获取有效的回复，请尝试使用不同的表述方式。";
                }
    
                // 处理异步响应 - 实现轮询机制
                if (result.status == "in_progress")
                {
                    _logger.LogWarning("AI21 API request is still in progress, will poll for completion");
                    
                    // 调用轮询方法等待结果完成
                    return await PollForCompletionAsync(result.id);
                }
                else if (result.status != "completed")
                {
                    _logger.LogError("AI21 API returned unexpected status: {Status}", result.status);
                    return $"AI服务返回了非预期状态: {result.status}，请稍后再试。";
                }
    
                // 直接提取回复内容（不再使用ExtractAssistantReply方法）
                string assistantReply = string.Empty;
                
                // 简单直接的实现方式
                try
                {
                    // 将result对象转换回JSON字符串，然后再尝试解析
                    string resultJson = JsonSerializer.Serialize(result.result);
                    _logger.LogInformation("Result JSON: {ResultJson}", resultJson);
                     
                    // 最直接的方式：如果result不是null，就显示它的字符串表示
                    if (result.result != null)
                    {
                        assistantReply = result.result.ToString() ?? "";
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError("Error extracting assistant reply: {Message}", ex.Message);
                }
                
                if (string.IsNullOrEmpty(assistantReply))
                {
                    _logger.LogError("AI21 API returned an empty response content");
                    _logger.LogInformation("Complete response for debugging: {ResponseBody}", responseBody);
                    return "未能获取有效的回复内容，请稍后再试。";
                }
    
                _logger.LogInformation("Successfully received response from AI21, response length: {ResponseLength}", assistantReply.Length);
    
                // 更新对话历史
                history.Add(new ChatMessage { Role = "user", Content = message });
                history.Add(new ChatMessage { Role = "assistant", Content = assistantReply });
    
                // 限制对话历史长度，防止过长
                if (history.Count > 20)
                {
                    history.RemoveRange(0, history.Count - 20);
                    _logger.LogInformation("Conversation history trimmed to {NewHistoryCount} messages", history.Count);
                }
    
                return assistantReply;
            }
            catch (Exception ex)
            {
                _logger.LogError("Unexpected error in ProcessMessageAsync: {Message}", ex.Message);
                _logger.LogError("Stack trace: {StackTrace}", ex.StackTrace);
                return "处理您的消息时发生未知错误，请稍后再试。";
            }
        }
        catch (Exception ex)
        {
            _logger.LogError("Unexpected error in ProcessMessageAsync: {Message}", ex.Message);
            _logger.LogError("Stack trace: {StackTrace}", ex.StackTrace);
            return "处理您的消息时发生未知错误，请稍后再试。";
        }
    }


    Task<bool> ICustomerService.ClearHistoryAsync(string userId)
    {
        throw new NotImplementedException();
    }

    Task<bool> ICustomerService.InitializeKnowledgeBaseAsync()
    {
        throw new NotImplementedException();
    }

    Task<string> ICustomerService.TestConnectionAsync()
    {
        throw new NotImplementedException();
    }

    // AI21 API 响应类 - 更新为匹配实际API响应格式
    public class AI21Response
    {
        [JsonPropertyName("id")]
        public string? id { get; set; }

        [JsonPropertyName("status")]
        public string? status { get; set; }

        [JsonPropertyName("result")]
        public object? result { get; set; }

        [JsonPropertyName("data_sources")]
        public object? data_sources { get; set; }

        [JsonPropertyName("requirements_result")]
        public object? requirements_result { get; set; }
    }


    private async Task<string> PollForCompletionAsync(string? runId)
    {
        if (string.IsNullOrEmpty(runId))
        {
            _logger.LogError("Invalid runId for polling");
            return "AI服务请求ID无效，请稍后再试。";
        }

        // 构建轮询URL - 使用runId查询结果
        string pollUrl = $"{_apiEndpoint}/{runId}";
        int maxRetries = 10; // 最大重试次数
        int retryDelayMs = 1000; // 每次重试间隔（毫秒）
        int retryCount = 0;

        while (retryCount < maxRetries)
        {
            try
            {
                _logger.LogInformation("Polling AI21 API for run completion, attempt {RetryCount}/{MaxRetries}",
                    retryCount + 1, maxRetries);

                // 等待一段时间再进行下一次轮询
                await Task.Delay(retryDelayMs);

                // 发送GET请求查询任务状态
                var pollResponse = await _httpClient.GetAsync(pollUrl);
                var pollResponseBody = await pollResponse.Content.ReadAsStringAsync();

                _logger.LogInformation("Poll response status: {StatusCode}", pollResponse.StatusCode);
                _logger.LogInformation("Poll response body: {ResponseBody}", pollResponseBody);

                if (!pollResponse.IsSuccessStatusCode)
                {
                    _logger.LogError("AI21 API polling error - Status: {StatusCode}, Content: {ErrorContent}",
                        pollResponse.StatusCode, pollResponseBody);
                    return $"AI服务轮询失败 [错误码: {pollResponse.StatusCode}]，请稍后再试。";
                }

                // 解析轮询响应
                AI21Response? pollResult = JsonSerializer.Deserialize<AI21Response>(pollResponseBody);

                if (pollResult == null)
                {
                    _logger.LogError("AI21 API returned null polling response");
                    retryCount++;
                    continue;
                }

                // 检查任务状态
                if (pollResult.status == "completed")
                {
                    _logger.LogInformation("AI21 API request completed successfully");

                    // 提取并返回助手回复（直接实现，不再调用单独方法）
                    string assistantReply = string.Empty;
                    try
                    {
                        if (pollResult.result != null)
                        {
                            // 将result对象转换回JSON字符串
                            string resultJson = JsonSerializer.Serialize(pollResult.result);
                            _logger.LogInformation("Completed result JSON: {ResultJson}", resultJson);

                            // 直接使用对象的字符串表示
                            assistantReply = pollResult.result.ToString() ?? "";
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("Error extracting completed result: {Message}", ex.Message);
                    }

                    if (string.IsNullOrEmpty(assistantReply))
                    {
                        assistantReply = "AI服务已完成处理，但未能获取到具体回复内容，请尝试使用不同的问题表述。";
                    }

                    return assistantReply;
                }
                else if (pollResult.status == "failed")
                {
                    _logger.LogError("AI21 API request failed: {ResponseBody}", pollResponseBody);
                    return "AI服务处理请求失败，请稍后再试。";
                }
                else if (pollResult.status == "in_progress")
                {
                    _logger.LogInformation("AI21 API request still in progress, continuing to poll");
                    retryCount++;
                }
                else
                {
                    _logger.LogWarning("AI21 API returned unexpected status during polling: {Status}", pollResult.status);
                    retryCount++;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Error during polling: {Message}", ex.Message);
                retryCount++;
            }
        }

        // 如果超过最大重试次数
        _logger.LogError("AI21 API polling timed out after {MaxRetries} attempts", maxRetries);
        return "AI服务处理请求超时，请稍后再试。";
    }
}


        // 轮询AI21 API以获取完成的结果
       

